package com.itzhoun.config;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * @author 周楠
 * @Date 2022/12/11/下午 4:09
 */
@Aspect
@Component
public class AopTemplate {


    @Pointcut("@annotation(com.itzhoun.config.CheckAop)")
    public void pointcut(){

    }

    @Before("pointcut()")
    public void deBefore(JoinPoint joinPoint){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        HttpServletRequest request = attributes.getRequest();

        //url
        System.out.println("url:" + request.getRequestURI());

        //HTTP_METHOD
        System.out.println("http_method" + request.getMethod());

        //class_method
        System.out.println("class_method" + joinPoint);

        //args参数
        System.out.println("args" + Arrays.toString(joinPoint.getArgs()));

        //获取切入点所在的目标对象
        Object target = joinPoint.getTarget();
        String name = target.getClass().getName();
        System.out.println("反射获取类名：" + name);

        //获取织入点所在的方法
        String nameMethod = joinPoint.getSignature().getName();
        System.out.println("反射获取类名,方法名" + nameMethod);

        //获取方法上的注解
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method != null){
            CheckAop annotation = method.getAnnotation(CheckAop.class);
            System.out.println("注解信息"+ annotation.isNeed());
        }

        for (Object arg : joinPoint.getArgs()) {
            System.out.println("参数打印"+ arg.toString());
        }


    }
}
